/*
 * Suman Gopal Pradhan
 * 
 * Example Usage
 * 	$("#selectImage").filebrowser({ onBrowse: function (data) {alert(data);},
                        fileHandler: 'Add_entry.aspx/FileBrowse'
                    });
 */

(function ($) {
    $.filebrowser = function (btn, options) {
        var $element = $(btn);
        var XHRRequest;

        var setOptions = function (newOptions) {

            options.onBrowse = newOptions.onBrowse;
            options.currentDir = '';
            options.fileHandler = newOptions.fileHandler;
        };

        var construct = function () {
            if ($('#filebrowser').length) return false;

            $('<div></div>').attr({
                id: 'filebrowser-overlay'
            }).css({
                display: 'none',
                position: 'absolute',
                left: 0,
                top: 0
            }).appendTo(document.body);

            $filebrowser = $('<div></div>').attr({
                id: 'filebrowser'
            }).css({
                display: 'none'
            }).appendTo(document.body);


            $('<ul></ul>').attr({
                id: 'filebrowser-browser'
            }).appendTo($filebrowser);



            $('<a></a>').attr({
                id: 'filebrowser-close',
                href: '#'
            }).text('Close').appendTo($filebrowser);


        };



        var bindEvents = function () {
            $('#filebrowser-close').unbind('click').bind('click', close);
        };




        var close = function (e) {
            hide();
            e.preventDefault();
        };

        var setTarget = function () {

            $element.bind('click', function () {
                setDir(options.currentDir);
                display();
            });
        };

        var display = function () {
            bindEvents();
            $('#filebrowser-overlay').css({
                display: 'block',
                width: $(document).width() + 'px',
                height: $(document).height() + 'px'
            });
            $('#filebrowser').css({
                display: 'block'
            });
        };

        var hide = function () {
            $('#filebrowser-browser').empty();
            $('#filebrowser-overlay').css({
                display: 'none'
            });
            $('#filebrowser').css({
                display: 'none'
            });


        };

        var setDir = function (dir) {

            options.current = null;

            if (XHRRequest) XHRRequest.abort();
            $('#filebrowser-currentpath').text(dir + "\\");

            var dta = { 'dir': dir };

            XHRRequest = $.ajax({
                url: options.fileHandler,
                type: 'POST',
                data: JSON.stringify(dta),
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                beforeSend: loadingBrowser,
                success: populateImages

            });
        };

        var loadingBrowser = function () {

            $('#filebrowser-browser').empty().addClass('loading');

        };


        var populateImages = function (files) {
            files = JSON.parse(files.d);

            $('#filebrowser-browser').removeClass('loading');
            $('#filebrowser-browser')[0].innerHTML = "";

            $.each(files, function (index, file) {
                options.currentDir = file.Path;
                $li = $('<li></li>').appendTo('#filebrowser-browser');

                if (file.IsDirectory) {
                    $a = $('<a></a>').appendTo($li);
                    $a.text(file.Name)
                    $('<img></img>').attr({
                        src: file.Icon
                    }).prependTo($a);
                    $a.attr({
                }).bind('click', function (e) {
                    e.preventDefault();
                    if (file.Name == "..") {
                        setDir(file.Path);
                    } else {
                        setDir(file.Path + "//" + file.Name);
                    }
                    return;
                });
            } else {
                var imgSrc = '/image.axd?picture=' + encodeURI(file.Name.replace(/\\/g, "/"));
                $img = $('<img></img>').appendTo($li);
                $img.attr({
                    src: imgSrc,
                    width: 100,
                    height: 100
                }).hover(function (e) {
                    e.preventDefault();
                    var $el = $(e.target);
                    if ($el.get(0).tagName.toLowerCase() != 'img') $el = $el.parent('img');
                    if (options.current) {
                        options.current.removeClass('selected');
                    }
                    $el.addClass('selected');
                    options.current = $el;
                    options.currentFile = file;
                }).bind("dblclick", function () { if (!file.IsDirectory) { onBrowse("<img src='" + imgSrc + "' />"); hide(); } });
            }
        });
    };


    var onBrowse = function (file) {
        options.onBrowse(file);
    };

    this.setOptions = setOptions;

    setOptions(options);
    construct();
    setTarget();
};

//singleton
$.fn.filebrowser = function (options) {
    this.each(function () {
        if ($(this).data('filebrowser')) {
            if (options.remove) {
                $(this).data('filebrowser').remove();
                $(this).removeData('filebrowser');
            } else {
                $(this).data('filebrowser').setOptions(options);
            }
        } else {
            $(this).data('filebrowser', new $.filebrowser(this, options));
        }
    });

    return this;
};
})(jQuery);